import React, { Component } from "react";
import { connect } from "dva";
import { Input, Form, Icon, Button, Select } from "antd";
import styles from "./ChainInputBox.less";

const { Option } = Select;

@connect(stores => ({
  pushAppData: stores.pushApp
}))
class SceneDataChainInputBox extends Component {
  state = {
    value: [],
    selectedSceneType: []
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: "pushScene/getSceneType" });
    dispatch({ type: "pushApp/getDataSource" });
    dispatch({ type: "pushApp/getDataAccessMethod" });
    dispatch({ type: "pushApp/getFiledName" });
    dispatch({ type: "pushApp/getDataHub" });
  }

  static getDerivedStateFromProps(nextProps) {
    if ("value" in nextProps) {
      return {
        value: nextProps.value,
        selectedSceneType: (nextProps.value || []).map(
          ({ sceneType } = {}) => sceneType
        )
      };
    }
    return null;
  }

  render() {
    const { onChange, max } = this.props;
    const { value, selectedSceneType } = this.state;
    return (
      <div className={styles.boxRoot}>
        {!(value || []).length && (
          <SceneDataChainInput
            selectedSceneType={selectedSceneType}
            onChange={allValues => {
              const temp = JSON.parse(JSON.stringify(value || []));
              temp[0] = allValues;
              onChange(temp);
            }}
          />
        )}
        {(value || []).map((item, index) => (
          <div key={index} className={styles.ChainInput}>
            <SceneDataChainInput
              value={item}
              selectedSceneType={selectedSceneType}
              onChange={allValues => {
                const temp = JSON.parse(JSON.stringify(value || []));
                temp[index] = allValues;
                onChange(temp);
              }}
            />
            <Icon
              type="close"
              className={styles.closeButton}
              onClick={() => {
                const temp = JSON.parse(JSON.stringify(value || []));
                temp.splice(index, 1);
                onChange(temp);
              }}
            />
          </div>
        ))}
        <Button
          shape="circle"
          icon="plus"
          size="small"
          className={styles.addButton}
          disabled={max ? (value || []).length >= max : false}
          onClick={() => {
            const temp = JSON.parse(JSON.stringify(value || []));
            temp.push({});
            onChange(temp);
          }}
        />
      </div>
    );
  }
}

export default SceneDataChainInputBox;

@connect(stores => ({
  pushAppData: stores.pushApp,
  sceneTypeList: stores.pushScene.sceneTypeList
}))
@Form.create({
  onValuesChange: ({ onChange }, changedValues, allValues) => {
    if (onChange) {
      onChange(allValues);
    }
  }
})
class SceneDataChainInput extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputsValue: props.value
    };
  }

  componentDidMount() {
    const {
      form: { setFieldsValue },
      value = {}
    } = this.props;
    setFieldsValue(value);
  }

  static getDerivedStateFromProps(nextProps) {
    if ("value" in nextProps) {
      return {
        inputsValue: nextProps.value
      };
    }
    return null;
  }

  componentDidUpdate() {
    const {
      form: { getFieldsValue }
    } = this.props;
    if (
      JSON.stringify(getFieldsValue()) !==
      JSON.stringify(this.state.inputsValue)
    ) {
      this.props.form.resetFields();
      this.props.form.setFieldsValue(this.state.inputsValue);
    }
  }

  render() {
    const {
      form: { getFieldDecorator, getFieldsValue, setFieldsValue },
      pushAppData: {
        dataAccessMethodList = [],
        dataSourceList = [],
        filedNameList = [],
        tableList = []
      },
      sceneTypeList = [],
      selectedSceneType = []
    } = this.props;
    const { dataSource } = getFieldsValue();
    let fieldCodeItem;
    if (dataSource === "F1") {
      fieldCodeItem = getFieldDecorator("fieldCode", {
        initialValue: undefined
      })(
        <Select placeholder={"字段名"} style={{ width: "150px" }}>
          {filedNameList.map(({ filedName }) => (
            <Option value={filedName} key={filedName}>
              {filedName}
            </Option>
          ))}
        </Select>
      );
    } else if (dataSource === "F2") {
      fieldCodeItem = getFieldDecorator("tableCode", {
        initialValue: undefined
      })(
        <Select placeholder={"topicName"} style={{ width: "150px" }}>
          {tableList.map(({ topicName }) => (
            <Option value={topicName} key={topicName}>
              {topicName}
            </Option>
          ))}
        </Select>
      );
    } else {
      fieldCodeItem = getFieldDecorator("fieldCode", {
        initialValue: undefined
      })(
        <Input
          maxLength={30}
          placeholder={"字段名"}
          style={{ width: "150px" }}
        />
      );
    }
    let logdataFieldItem;
    if (dataSource === "F1") {
      logdataFieldItem = getFieldDecorator("logdataField", {
        initialValue: "API"
      })(
        <Input
          disabled={true}
          placeholder={"数据来源"}
          style={{ width: "150px" }}
        />
      );
    } else if (dataSource === "F2") {
      logdataFieldItem = getFieldDecorator("tableProject", {
        initialValue: undefined
      })(
        <Select placeholder={"projectName"} style={{ width: "150px" }}>
          {tableList.map(({ projectName }) => (
            <Option value={projectName} key={projectName}>
              {projectName}
            </Option>
          ))}
        </Select>
      );
    } else {
      logdataFieldItem = getFieldDecorator("logdataField", {
        initialValue: undefined
      })(
        <Select placeholder={"数据来源"} style={{ width: "150px" }}>
          {dataSourceList.map(({ valueDesc, id: dataSourceId }) => (
            <Option value={dataSourceId} key={dataSourceId}>
              {valueDesc}
            </Option>
          ))}
        </Select>
      );
    }
    return (
      <div className={styles.inputRoot}>
        {getFieldDecorator("dataSource", {
          initialValue: undefined
        })(
          <Select
            placeholder={"数据接入方式"}
            onChange={value => {
              setFieldsValue({
                logdataField: value === "F1" ? "API" : undefined,
                projectName: undefined,
                fieldCode: undefined,
                tableCode: undefined
              });
            }}
            style={{ width: "150px" }}
          >
            {dataAccessMethodList.map(
              ({ valueDesc, dataValue: dataAccessMethodId }) => (
                <Option value={dataAccessMethodId} key={dataAccessMethodId}>
                  {valueDesc}
                </Option>
              )
            )}
          </Select>
        )}
        <span className={styles.dash}>&nbsp;&nbsp;——&nbsp;&nbsp;</span>
        {getFieldDecorator("sceneType", {
          initialValue: undefined
        })(
          <Select placeholder={"场景类型"} style={{ width: "150px" }}>
            {sceneTypeList.map(({ valueDesc, id: sceneTypeId }) => (
              <Option
                value={sceneTypeId}
                key={sceneTypeId}
                disabled={selectedSceneType.indexOf(sceneTypeId) !== -1}
              >
                {valueDesc}
              </Option>
            ))}
          </Select>
        )}
        <span className={styles.dash}>&nbsp;&nbsp;——&nbsp;&nbsp;</span>
        {logdataFieldItem}
        <span className={styles.dash}>&nbsp;&nbsp;——&nbsp;&nbsp;</span>
        {fieldCodeItem}
      </div>
    );
  }
}
